package cn.edu.zhku.citrusmonitor.util;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		// 获取请求方法名
		String methodName = request.getParameter("method");
		try {
			if(methodName == null) {
				methodName = "index";
			}
			//methodName = methodName.substring(0, methodName.lastIndexOf(".do"));
			// 通过反射拿到目标方法
			Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			if (method != null) {
				Object obj = method.invoke(this, request, response);
				if (obj != null) {
					// 将信息写回页面
					response.getWriter().print(obj);
				}
			}
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
			request.getRequestDispatcher("/404.html").forward(request, response);
		}
	}
		
}
